/*
 * pi3's Linux kernel Runtime Guard
 *
 * Component:
 *  - Intercept *call_usermodehelper_exec* function
 *
 * Notes:
 *  - We are maintianing Red-Black tree of pid's for Exploit Detection feature.
 *    When kernel calls user-mode helper, we need to verify task's integrity
 *
 * Caveats:
 *  - None
 *
 * Timeline:
 *  - Created: 01.IV.2019
 *
 * Author:
 *  - Adam 'pi3' Zabrocki (http://pi3.com.pl)
 *
 */

#include "../../../../p_lkrg_main.h"


char p_call_usermodehelper_exec_kretprobe_state = 0;

static struct kretprobe p_call_usermodehelper_exec_kretprobe = {
    .kp.symbol_name = "call_usermodehelper_exec",
    .handler = p_call_usermodehelper_exec_ret,
    .entry_handler = p_call_usermodehelper_exec_entry,
    .data_size = sizeof(struct p_call_usermodehelper_exec_data),
    /* Probe up to 40 instances concurrently. */
    .maxactive = 40,
};

int p_call_usermodehelper_exec_entry(struct kretprobe_instance *p_ri, struct pt_regs *p_regs) {

   struct p_ed_process *p_tmp;
   unsigned long p_flags;

   p_ed_pcfi_cpu(1);

   if (p_is_ed_task(current)) {
      p_tasks_read_lock(&p_flags);
      p_ed_validate_current();
      if ( (p_tmp = p_find_ed_by_pid(task_pid_nr(current))) != NULL) {
         if (p_ed_enforce_pcfi(current, p_tmp, p_regs)) {
            p_print_log(P_LKRG_CRIT,
                   "<Exploit Detection> Stack pointer corruption (ROP?) - pCFI violation: process[%s | %d] !!!\n",
                   current->comm,task_pid_nr(current));
            p_pcfi_kill_task_by_task(current);
         }
      }
      p_tasks_read_unlock(&p_flags);
   }

   return 0;
}

int p_call_usermodehelper_exec_ret(struct kretprobe_instance *ri, struct pt_regs *p_regs) {

   return 0;
}


GENERATE_INSTALL_FUNC(call_usermodehelper_exec)
